package xhwl.insurance.ui;

import android.os.Bundle;

import java.util.ArrayList;

import xhwl.android.common.util.SPUtil;
import xhwl.insurance.R;
import xhwl.insurance.BaseActivity;
import xhwl.insurance.adapter.ResultsEndorsementAdapter;
import xhwl.insurance.customView.PullToRefreshListView;
import xhwl.insurance.http.api.ResultsEndorsementApi;
import xhwl.insurance.http.bean.resp.SanJiFenXiaoResp;
import xhwl.insurance.util.XHLog;
import xhwl.retrofitrx.HttpException;
import xhwl.retrofitrx.HttpManager;
import xhwl.retrofitrx.OnNextListener;

/**
 * 我的代言成果
 * Created by chengang on 2017/6/7.
 */

public class ResultsEndorsementActivity extends BaseActivity implements PullToRefreshListView.RefreshListener {

    private PullToRefreshListView pullToRefreshListView;
    private ResultsEndorsementAdapter adapter;
    private ArrayList<SanJiFenXiaoResp> mlistVo = new ArrayList<SanJiFenXiaoResp>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.results_endorsement);
    }

    @Override
    public void initViews() {
        initTitleViews();
        pullToRefreshListView = (PullToRefreshListView) findViewById(R.id.pullToRefreshListView);
        adapter = new ResultsEndorsementAdapter(ResultsEndorsementActivity.this, mlistVo);
        pullToRefreshListView.setAdapter(adapter);
    }

    @Override
    protected void setUpTitleView() {
        titleTextView.setText("我的代言成果");
        super.setUpTitleView();
    }

    @Override
    public void initListener() {
        pullToRefreshListView.setRefreshListener(this);
    }

    @Override
    public void loadData() {
        requestList(1);
    }

    @Override
    public void onRefresh(int page) {
        requestList(page);
    }

    private void requestList(int page) {
        String link_phone = SPUtil.getPersonInfoSp().getString(SPUtil.SPPersonInfo.LINK_MOBILE, "");
        ResultsEndorsementApi api = new ResultsEndorsementApi(page + "", link_phone);

        HttpManager.getInstance().dealHttp(this, api, new OnNextListener<ArrayList<SanJiFenXiaoResp>>() {

            @Override
            public void onNext(ArrayList<SanJiFenXiaoResp> resp) {
                try {
                    pullToRefreshListView.onRefreshComplete(mlistVo, resp.size());
                    mlistVo.addAll(resp);
                    adapter.notifyDataSetChanged();
                } catch (Exception e) {
                    XHLog.e(e.getMessage());
                    pullToRefreshListView.onRefreshComplete();
                }
            }

            @Override
            public void onError(HttpException ex) {
                super.onError(ex);
                pullToRefreshListView.onRefreshComplete();
            }
        });
    }
}
